package com.lagou.rabbitmq.payorder.controller;

import com.lagou.rabbitmq.payorder.dao.Order;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ascetic
 * @version 1.0
 * @ClassName payController
 * @Description TODO
 * @date 2021-03-13 18:54
 */
@Controller
@RequestMapping("/")
public class PayController {

    @Autowired
    private AmqpTemplate rabbitTemplate;

    List<Order> orders = new ArrayList<>();


    @RequestMapping(value = "login")
    public String index(){
        System.out.println("index");
        return "index";
    }

    @RequestMapping(value = "order",method = RequestMethod.POST)
    public String order(Model model){
        // 向rabbitmq 里发送消息，然后跳转到等待付款页面
        System.out.println("==下单==");
        String orderId =((int)(Math.random()*100))+"";
        rabbitTemplate.convertAndSend("ex.order","order",orderId);

        orders.add(new Order(orderId,"未付款"));

        model.addAttribute("orderId",orderId);
        return "forward:/waitingpay";
    }

    @RequestMapping(value = "waitingpay")
    public String waitingpay(){

        return "waitingpay";
    }

    @RequestMapping("pay")
    public String pay(String orderId,Model model) {

        model.addAttribute("orders",orders);
        for (Order order : orders) {
            System.out.println(orderId + order.getOrderId());
            if (order.getOrderId().equals(orderId)) {
                if (order.getStatus().equals("已超时")) {
                    // 付款订单已经超时，直接跳转到超时页面
                    return "timeout";
                } else {
                    order.setStatus("已付款");
                    return "success";
                }
            }
        }
        return "timeout";
    }

    @RabbitListener(queues ="timeoutOrder.dlx")
    public void getTimeOutOrder(@Payload String message){
        System.out.println("订单:"+message+"已经超时...");
        for (Order order : orders) {
            if (order.getOrderId().equals(message)
                    && !order.getStatus().equals("已付款")) {
                order.setStatus("已超时");
            }
        }
    }

}